//
//  CXLDetaileView.m
//  WYNews
//
//  Created by 夜猫子 on 2017/3/18.
//  Copyright © 2017年 夜猫子. All rights reserved.
//

#import "CXLDetaileView.h"
#import "CXLDetailsLabel.h"
#import "CXLDetailsModel.h"

#define labelHeight 40
const NSInteger _basrTag = 666;



@implementation CXLDetaileView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //数组获取到模型数组的值
        _modelArr = [CXLDetailsModel topicDataList];
        self.backgroundColor = [UIColor whiteColor];
        [self setupUI];
        
    }
    return self;
}


- (void)setupUI {
    //隐藏水平滚动条
    self.showsHorizontalScrollIndicator = NO;
    
    CGFloat origin = 0;
    
    NSInteger index = 0;
    
    for (CXLDetailsModel *model in _modelArr) {
        
        CXLDetailsLabel *lable = [CXLDetailsLabel labelWithModel:model];
        
        CGRect frame = CGRectMake(origin, 0, lable.bounds.size.width, labelHeight);
        lable.frame = frame;
        
        origin += lable.bounds.size.width;
        
        [self addSubview:lable];
        //默认是未选中状态
        lable.isSelected = NO;
        lable.tag = _basrTag + index;
        //开启lable的交互
        lable.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(detailsWithTap:)];
        if (index == 0) {
            lable.isSelected = YES;
        }
        
        [lable addGestureRecognizer:tap];
        
        index += 1;
        
    }
    
//    self.isSelegte = 0;
    
    self.contentSize = CGSizeMake(origin, labelHeight);
    
}


- (void)detailsWithTap:(UITapGestureRecognizer *)tap {
    
    CXLDetailsLabel *lable = (CXLDetailsLabel *)tap.view;
    NSInteger index = lable.tag - _basrTag;
    //设置当前选中的index,重写了setIsSelegte属性的set方法,当改变setIsSelegte值的时候,可以同时改变lable的选中状态
    [self setIsSelegte:index];
    
    if (_detailDelegte && [_detailDelegte respondsToSelector:@selector(detailView:)]) {
        
        [_detailDelegte detailView:index];
        
    }
    
}


- (void)setIsSelegte:(NSInteger)isSelegte {
//    NSLog(@"isSelegte:%zd",isSelegte);
//    NSLog(@"_isSelegte:%zd",_isSelegte);
    
    if (_isSelegte == isSelegte) {
        return;
    }
    
    //取消选中状态
    CXLDetailsLabel *selLabel = [self viewWithTag:_isSelegte + _basrTag];
    selLabel.isSelected = NO;
  
    
    //选中状态r
    CXLDetailsLabel *label = [self viewWithTag:isSelegte + _basrTag];
    label.isSelected = YES;
    
    CGFloat leftX = label.frame.origin.x;
    CGFloat rightX = label.frame.origin.x + label.bounds.size.width;
    CGFloat centerX = self.contentOffset.x;
    
    
    if (leftX < centerX || rightX > centerX) {
        
        [self scrollRectToVisible:label.frame animated:YES];
        
    }
    
    
    _isSelegte = isSelegte;
}


@end
